package cn.itsource.org.service.impl;

import cn.itsource.basic.constant.PethomeConstant;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.utils.MD5Utils;
import cn.itsource.basic.utils.StrUtils;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.org.service.IShopService;
import cn.itsource.user.domain.LoginInfo;
import cn.itsource.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 店铺service的实现类
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private ShopMapper shopMapper;


    @Override
    @Transactional
    public void settledIn(Shop shop) {
        //保存店铺（店铺主键id有值了）
        super.save(shop);//保存店铺，但是admin_id是为空的
        //获取员工对象
        Employee admin = shop.getAdmin();
        admin.setSalt(StrUtils.getComplexRandomString(10));
        admin.setPassword(MD5Utils.encrypByMd5(admin.getPassword()+admin.getSalt()));
        //创建登录信息对象
        LoginInfo loginInfo = createLoginInfo(admin);
        logininfoMapper.save(loginInfo);

        admin.setLoginInfo(loginInfo);
        admin.setShop(shop);//因为保存员工的时候，需要设置所属店铺
        employeeMapper.save(admin);//因为保存了之后店铺才有值
        //修改店铺
        super.update(shop);//更新admin_id

    }

    @Override
    public Shop loadByLogininfoid(Long logininfoid) {
        return shopMapper.loadByLogininfoid(logininfoid);
    }

    private LoginInfo createLoginInfo(Employee admin) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(admin, loginInfo);
        loginInfo.setType(PethomeConstant.ADMIN);
        return loginInfo;
    }
}
